package com.shioirikukuri.controller;

import com.shioirikukuri.common.result.Result;
import com.shioirikukuri.entity.User;
import com.shioirikukuri.service.ICustomerService;
import com.shioirikukuri.service.IUserService;
import com.shioirikukuri.util.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;
import java.util.Random;

@RestController
@RequestMapping("/sms")
public class SmsController {

	@Autowired
	private SmsService smsService;

	@Autowired
	private IUserService userService;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Autowired
	private ICustomerService customerService;

	/**
	 * 发送短信验证码接口
	 */
	@PostMapping("/send")
	public Result<String> sendCode(@RequestParam String phoneNumber) {
		try {
			String code = generateRandomCode(); // 生成随机验证码
			smsService.sendCode(phoneNumber, code);
			return Result.success("短信发送成功");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(500,"短信发送失败");
		}
	}

	/**
	 * 消费者使用验证码登录接口
	 * 登录时检查是否存在用户，存在则登录，否则自动创建新用户
	 *
	 * @param phoneNumber 手机号
	 * @param code        验证码
	 * @return 登录结果（Result<String> 格式）
	 */
	@PostMapping("/login")
	public Result<String> login(@RequestParam String phoneNumber, @RequestParam String code) {
		try {
			// 1. 校验验证码是否正确
			if (!smsService.verifyCode(phoneNumber, code)) {
				return Result.error(400, "验证码错误");
			}

			// 2. 检查是否被拉黑
			if (userService.isUserBlacklisted(phoneNumber)) {
				return Result.error(403, "该用户已被拉黑");
			}

			// 3. 查询是否已有该手机号的用户
			Optional<User> existingUserOpt = customerService.findConsumerByPhoneNumber(phoneNumber);

			User user;
			if (existingUserOpt.isPresent()) {
				// 用户已存在，直接登录
				user = existingUserOpt.get();
			} else {
				// 用户不存在，创建新用户
				User newUser = new User();
				newUser.setPhoneNumber(phoneNumber);
				// 设置默认字段
				newUser.setFullName(phoneNumber); // 默认姓名为手机号
				newUser.setPassword(""); // 密码为空
				newUser.setRole("CONSUMER"); // 角色为消费者
				newUser.setEnabled(User.ENABLED); // 状态启用
				newUser.setAvatarUrl(""); // 头像为空

				user = userService.addUser(newUser);
			}

			// 4. 构造登录成功响应（例如返回用户ID或token）
			String loginSuccessMessage = String.format("登录成功，用户ID：%d", user.getId());
			return Result.success(loginSuccessMessage);

		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(500, "登录失败");
		}
	}

	public String generateRandomCode() {
		Random random = new Random();
		// 生成从1000到9999的随机整数，确保是4位数
		int code = 1000 + random.nextInt(9000);
		return String.valueOf(code);
	}
}